package com.example.dao.impl;

import com.example.dao.UserDao;
import com.example.model.Carousel;
import com.example.model.User;
import com.example.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class UserDaoImpl implements UserDao {
    @Override
    public User getUserByUsername(String username) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select id,username,password,nickname from tb_user where username = ?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            rs = ps.executeQuery();
            while(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setNickName(rs.getString("nickname"));
                return user;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.close(connection,ps,rs);
        }
        return user;
    }

    @Override
    public void updateByUsername(User user) {
        Connection connection = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "update tb_user set nickname = ?, headportrait=? where username = ?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,user.getNickName());
            ps.setString(2,user.getHeadPortrait());
            ps.setString(3,user.getUsername());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.close(connection,ps,rs);
        }
    }
}
